package com.crealth.crmserver;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.crealth.Config;
import com.crealth.db.UserDb;

public class CRMServer extends Thread {
	private static Logger logger = Logger.getLogger("running_log");
	private static int LISTEN_PORT;
	
	@Override
    public void run() {
		LISTEN_PORT = Config.CRMPort;
		
		initData();
		startCRMServer();
	}
	
	private static void startCRMServer() {
        IoAcceptor acceptor = null;
        try {
            acceptor = new NioSocketAcceptor();
            //WhitelistFilter whitelistFilter = new WhitelistFilter();   
            //acceptor.getFilterChain().addFirst("white", whitelistFilter);            
            acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CRMServerCodecFactory()));
            acceptor.getSessionConfig().setReadBufferSize(10*1024);
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30000);
            acceptor.setHandler(new CRMServerHandler());
            acceptor.bind(new InetSocketAddress(LISTEN_PORT));
            
            SessionManager.setClientSessions(acceptor.getManagedSessions());
            logger.info("CRMServer 服务端启动成功...  端口号为: " + LISTEN_PORT);
        }
        catch (Exception e) {
            logger.error("CRMServer 服务端启动异常.... 端口号为: " + LISTEN_PORT);
            logger.error("", e);
            System.exit(-1);
        }
    }
	
	//  初始化  全局的数据
	private void initData() {
		UserDb.cleanOnlineUser();
	}
	
	
}
